package org.example;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;

@Service
public class TimerTaskService {

    private static final DateTimeFormatter FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 每秒输出当前时间
     */
    @Async("threadPoolExecutor")
    public CompletableFuture<Void> printCurrentTimeEverySecond(int durationSeconds) {
        System.out.println("开始执行每秒输出时间任务，持续" + durationSeconds + "秒...");

        for (int i = 0; i < durationSeconds; i++) {
            try {
                Thread.sleep(1000); // 休眠1秒
                String currentTime = LocalDateTime.now().format(FORMATTER);
                System.out.println("当前时间: " + currentTime + " (" + (i + 1) + "/" + durationSeconds + ")");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("任务被中断");
                break;
            }
        }

        System.out.println("每秒输出时间任务完成");
        return CompletableFuture.completedFuture(null);
    }

    /**
     * 倒计时任务
     */
    @Async("threadPoolExecutor")
    public CompletableFuture<Void> countdownTask(int seconds) {
        System.out.println("开始倒计时：" + seconds + "秒");

        for (int i = seconds; i > 0; i--) {
            try {
                System.out.println("倒计时: " + i + "秒");
                Thread.sleep(1000); // 休眠1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("倒计时任务被中断");
                break;
            }
        }

        System.out.println("倒计时结束！");
        return CompletableFuture.completedFuture(null);
    }

    /**
     * 模拟耗时计算任务
     */
    @Async("threadPoolExecutor")
    public CompletableFuture<Long> calculateFactorial(int number) {
        System.out.println("开始计算 " + number + " 的阶乘...");

        long result = 1;
        for (int i = 1; i <= number; i++) {
            result *= i;
            try {
                Thread.sleep(500); // 模拟计算耗时
                System.out.println("计算中... " + i + "/" + number);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("计算任务被中断");
                break;
            }
        }

        System.out.println(number + " 的阶乘 = " + result);
        return CompletableFuture.completedFuture(result);
    }
}